<template>
  <a-card :bordered="false" style="margin:0;">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <!-- 搜索区域 -->
      <a-form layout="inline">
        <a-row :gutter="10">
          <a-col :md="10" :sm="12">
            <a-form-item label="文件名" style="margin-left:8px">
              <a-input placeholder="请输入文件名" v-model="queryParam.username"></a-input>
            </a-form-item>
          </a-col>
          <!--<a-col :md="8" :sm="8">-->
          <!--<a-form-item label="用户名称" :labelCol="{span: 5}" :wrapperCol="{span: 18, offset: 1}">-->
          <!--<a-input placeholder="请输入名称查询" v-model="queryParam.realname"></a-input>-->
          <!--</a-form-item>-->
          <!--</a-col>-->
          <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
            <a-col :md="6" :sm="24">
             <a-button type="primary" @click="searchQuery" icon="search" style="margin-left: 18px">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
            </a-col>
          </span>
        </a-row>
        </a-form>
               <!-- 已有文件弹窗 -->
                   <a-modal v-model="FileModalVisible" title="选择已有文件" @ok="FileModalOk" width="800px">
                     <a-input placeholder="请输入文件名" v-model="fileName" style="width: 240px" />
                     <a-button type="primary" @click="searchFile" icon="search" style="margin-left: 18px">查询</a-button>
                     <a-table
                       style="margin-top: 15px;"
                       bordered
                       rowKey="id"
                       :row-selection="{ selectedRowKeys: selectedFileRowKeys, onChange: onSelectFileChange }"
                       :columns="columnsFile"
                       :data-source="dataFile"
                     />
               </a-modal>
    </div>
    <!-- 操作按钮区域 -->
    <div class="table-operator" :md="24" :sm="24" style="margin-top: -15px">
      <!--<a-button @click="" type="primary" icon="edit" style="margin-top: 16px">用户编辑</a-button>-->
      <a-button :disabled="selectedKeys.length ? false : true " @click="getFileModal" type="primary" icon="plus" >挂接文件池</a-button>
      <!--<a-button :disabled="selectedKeys.length ? false : true " @click="" type="primary" icon="plus" style="margin-top: 16px">新建文件</a-button>-->
      <!--<a-upload
        name="file"
        :showUploadList="false"
        :multiple="false"
        action=""
        :headers="headers"
        @change="handleChange"
      >
        <a-button :disabled="selectedKeys.length ? false : true " type="primary" style="margin-left: 16px"> <a-icon type="plus" /> 新建文件 </a-button>
      </a-upload>-->
      <DtgUploadFile :fileDisabled="selectedKeys.length ? false : true "
                     :fileList="fileList"
                     @changeFile="handleChange">
      </DtgUploadFile>

      <!--<a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel">
            <a-icon type="delete"/>
            取消关联
          </a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作
          <a-icon type="down"/>
        </a-button>
      </a-dropdown>-->
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{
        selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        @change="handleTableChange">

        <span slot="action" slot-scope="text, record">
          <a @click="handleView(record)">预览</a>
          <a-divider type="vertical"/>
          <a @click="handleDelete(record.id)">删除</a>

          <!--<a-dropdown>
            <a class="ant-dropdown-link">
              更多 <a-icon type="down"/>
            </a>
            <a-menu slot="overlay">
                <a-menu-item>
                <a href="javascript:;" @click="handleEdit(record)">编辑</a>
              </a-menu-item>

              <a-menu-item>
                <a href="javascript:;" @click="handleDetail(record)">详情</a>
              </a-menu-item>

              <a-menu-item>
                <a-popconfirm title="确定取消与选中部门关联吗?" @confirm="() => handleDelete(record.id)">
                  <a>取消关联</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>-->
        </span>


      </a-table>
    </div>
    <!-- table区域-end -->

    <!-- 表单区域 -->
    <!--<DocHookUpModal ref="modalForm" @ok="modalFormOk"></DocHookUpModal>-->
    <!--<Select-User-Modal ref="selectUserModal" @selectFinished="selectOK"></Select-User-Modal>-->
    <!--<dept-role-user-modal ref="deptRoleUser"></dept-role-user-modal>-->



    <!-- 预览 -->
    <!--<ViewDoc :fileSrc="fileSrc"></ViewDoc>-->
    <a-modal :width="1200" :dialog-style="{ top: '0px' }" :visible="previewVisible" :footer="null" @cancel="handleCancel">
      <viewDoc :viewDocData="viewDocData"></viewDoc>
    </a-modal>

  </a-card>
</template>

<script>
  import {JeecgListMixin} from '@/mixins/JeecgListMixin'
  import {getAction, postAction, deleteAction} from '@/api/manage'
  // import SelectUserModal from './SelectUserModal'
  import DocHookUpModal from './DocHookUpModal'
  import EquipmentMmodal from './EquipmentMmodal'
  import { dtgTypeDetailsAdd,dtgTypeDetailsEdit,fileTransManageAdd,
  dtgEquipmentInfoEdit,getEquipmentInfoListNoPid,getFileDetailsInfoList  } from '@/api/digitization'
  import DtgUploadFile from './DtgUploadFile'
  import ViewDoc from '../ViewDoc'
  let Base64 = require('js-base64').Base64

  export default {
    name: "DeptUserInfo",
    mixins: [JeecgListMixin],
    components: {
      // DeptRoleUserModal,
      // SelectUserModal,
      DocHookUpModal,EquipmentMmodal,DtgUploadFile,ViewDoc
    },
    data() {
      return {
        headers: {
          authorization: 'authorization-text',
        },
        description: '文件信息',
        currentDeptId: '',
        // 表头
        columns: [
          {
            title: '文件名称',
            align: "center",
            dataIndex: 'fileTitle'
          },
          {
            title: '文件类型',
            align: "center",
            dataIndex: 'fileTypes'
          },
          {
            title: '大小(MB)',
            align: "center",
            dataIndex: 'fileSize',
            customRender: function (t, r, index) {
              let size = (parseInt(t) / 1024 / 1024).toFixed(2);
              return size < 0.1 ? '不足0.1MB' : size ;
            }
          },
          {
            title: '版本',
            align: "center",
            dataIndex: 'versionNo'
          },
          {
            title: '创建时间',
            align: "center",
            dataIndex: 'createTime'
          },
          {
            title: '操作',
            dataIndex: 'action',
            scopedSlots: {customRender: 'action'},
            align: "center",
            width: 150
          }],
          columnsFile:[
            {
              title: '#',
              dataIndex: '',
              key:'rowIndex',
              width:60,
              align:"center",
              customRender:function (t,r,index) {
                return parseInt(index)+1;
              }
            },
            {
              title:'创建人',
              align:"center",
              dataIndex: 'createBy'
            },
            {
              title:'创建日期',
              align:"center",
              dataIndex: 'createTime',
              customRender:function (text) {
                return !text?"":(text.length>10?text.substr(0,10):text)
              }
            },
            {
              title:'编号',
              align:"center",
              dataIndex: 'fileCode'
            },
            {
              title:'文件名',
              align:"center",
              dataIndex: 'fileTitle'
            },
            {
              title:'编制单位',
              align:"center",
              dataIndex: 'orgBelong'
            },
            {
              title:'文档格式',
              align:"center",
              dataIndex: 'fileTypes'
            },
          ],
        url: {
          list: "/base/fmFileDetailsInfo/getByPid",
          delete:"/base/fmFileDetailsInfo/delete"
        },
        FileModalVisible: false,
        userInfo: this.$store.getters.userInfo,
        fileSrc:'',
        selectedFileRowKeys:[],
        tableData:[],
        fileList:[],
        previewVisible: false,
        viewDocData:{},
        dataFile:[],
        fileName:''
      }
    },
    props:{
      tabData: {
          type: Array,
          default(){
            return []
          }
        },
      selectedKeys:{
        type: Array,
        default(){
          return []
        }
      },
      selectedKeysNode:{
        type: Object,
        default(){
          return {}
        }
      }
    },
    watch:{
      selectedKeys: {
        immediate: true,
        deep: true,
        handler(n,o) {
          console.log(n,'n');
          this.loadData();
        }
      },
    },
    created() {
      console.log(this.userInfo);
      //this.initTableData();
    },
    methods: {
      initTableData(){
        getEquipmentInfoListNoPid().then(res => {
          this.tableData = res.result.records;
        })
      },
       //选中已有文件弹窗
      getFileModal(){
        this.fileName = '';
        this.FileModalVisible = true;
        getFileDetailsInfoList().then(res => {
          this.dataFile = res.result.records;
        })
      },
      searchFile(){
              getFileDetailsInfoList({fileTitle: '*'+this.fileName+'*'}).then(res => {
                this.dataFile = res.result.records;
              })
            },
      FileModalOk(){
              this.FileModalVisible = false;
              this.handEdit();
       },
       handEdit(){
            this.$emit("filesHandler",this.selectedFileList)
       },
      onSelectFileChange(selectedRowKeys,row){
              this.selectedFileRowKeys = selectedRowKeys;
              this.selectedFileList = row;
       },
      equipmentChange(selData){
        this.selectedFileRowKeys = selData.selectedFileRowKeys;
      },
      handleEquipmentOk(selData){
        console.log(selData);

        let {createBy,createTime,updateBy,updateTime,orgCode} = this.userInfo;
        let {id,name,supplier_dictText} = selData.selectedFileList[0];

        let params = {};
        params = {
          id,    //所选设备的id
          createBy,
          createTime,
          updateBy,
          updateTime,
          sysOrgCode:orgCode,
          typeName:name,
          remark:supplier_dictText,
          pid:this.selectedKeys[0],
          lvIdx:'',
          lvIndex:'',
          hasChild:0
        }

        dtgTypeDetailsAdd(params).then(res => {
          this.$message.success(res.message);
          this.$emit('selExpanded',this.selectedKeys)

          dtgEquipmentInfoEdit({pid:this.selectedKeys[0], id}).then(res => {

          })


        })

      },
      searchReset() {
        this.queryParam = {}
        this.loadData(1);
        this.$emit('handleReset')
      },
      loadData(arg) {
        // debugger
        if (!this.url.list) {
          this.$message.error("请设置url.list属性!")
          return
        }
        //加载数据 若传入参数1则加载第一页的内容
        if (arg === 1) {
          this.ipagination.current = 1;
        }
        //if (this.currentDeptId === '') return;
        // let params = this.getQueryParams();//查询条件
        let params ={};
        if(this.selectedKeys && this.selectedKeys.length){
          params.pid = this.selectedKeys[0];
        }else{
          params.pid = '';
        }
        params.fileTitle = this.queryParam.username;
        getAction(this.url.list, params).then((res) => {
          if (res.success && res.result.length) {
            this.dataSource = res.result;
            // this.ipagination.total = res.result.total;
          }else{
            this.dataSource = [];
          }
        })
      },
      batchDel: function () {
        if (!this.url.deleteBatch) {
          this.$message.error("请设置url.deleteBatch属性!")
          return
        }
        if (!this.currentDeptId) {
          this.$message.error("未选中任何部门，无法取消部门与用户的关联!")
          return
        }

        if (this.selectedRowKeys.length <= 0) {
          this.$message.warning('请选择一条记录！');
          return;
        } else {
          var ids = "";
          for (var a = 0; a < this.selectedRowKeys.length; a++) {
            ids += this.selectedRowKeys[a] + ",";
          }
          var that = this;
          console.log(this.currentDeptId);
          this.$confirm({
            title: "确认取消",
            content: "是否取消用户与选中部门的关联?",
            onOk: function () {
              deleteAction(that.url.deleteBatch, {depId: that.currentDeptId, userIds: ids}).then((res) => {
                if (res.success) {
                  that.$message.success("删除用户与选中部门关系成功！");
                  that.loadData();
                  that.onClearSelected();
                } else {
                  that.$message.warning(res.message);
                }
              });
            }
          });
        }
      },
      handleDelete: function (id) {
        var that = this;
        deleteAction(that.url.delete, {id: id}).then((res) => {
          if (res.success) {
            that.$message.success("操作成功！");
            if (this.selectedRowKeys.length>0){
               for(let i =0; i<this.selectedRowKeys.length;i++){
                   if (this.selectedRowKeys[i] == id){
                     this.selectedRowKeys.splice(i,1);
                     break;
                   }
               }
            }
            that.loadData();
          } else {
            that.$message.warning(res.message);
          }
        });
      },
      open(record) {
        //console.log(record);
        if(record!=null&&record.id!=null)
          this.loadData(record.id);
        else
          this.loadData(1);

      },
      clearList() {
        this.currentDeptId = '';
        this.dataSource = [];
      },
      hasSelectDept() {
        if (this.currentDeptId == '') {
          this.$message.error("请选择一个部门!")
          return false;
        }
        return true;
      },
      handleAddUserDepart() {
        if (this.currentDeptId == '' ) {
          this.$message.error("请选择一个部门!")
        } else {
          this.$refs.selectUserModal.visible = true;
        }
      },
      /*handleEdit: function (record) {
        this.$refs.modalForm.title = "编辑";
        this.$refs.modalForm.departDisabled = true;
        this.$refs.modalForm.disableSubmit = false;
        this.$refs.modalForm.edit(record);
      },
      handleAdd: function () {
        if (this.currentDeptId == '') {
          this.$message.error("请选择一个部门!")
        } else {
          this.$refs.modalForm.departDisabled = true;
          this.$refs.modalForm.userDepartModel.departIdList = [this.currentDeptId];  //传入一个部门id
          this.$refs.modalForm.add();
          this.$refs.modalForm.title = "新增";
        }
      },*/
      handleView: function (record) {
      debugger
        let url = window._CONFIG['staticDomainURL']+ record.filePath; //要预览文件的访问地址
        //let codeUrl = Base64.encode(url);
        this.fileSrc = window._CONFIG['fileDomainURL'] + '/onlinePreview?url=' + encodeURIComponent(Base64.encode(url));

        /*let routeData = this.$router.resolve({
          path: '/digital/viewDoc',
          query: {fileSrc: this.fileSrc, fileData: JSON.stringify(record)},
        });
        window.open(routeData.href, '_blank');*/

        this.viewDocData = {fileSrc: this.fileSrc, fileData: JSON.stringify(record)}
        this.previewVisible = true;
      },
      handleCancel() {
        this.previewVisible = false;
        this.viewDocData = {};
      },
      selectOK(data) {
        let params = {};
        params.depId = this.currentDeptId;
        params.userIdList = [];
        for (var a = 0; a < data.length; a++) {
          params.userIdList.push(data[a]);
        }
        console.log(params);
        postAction(this.url.edit, params).then((res) => {
          if (res.success) {
            this.$message.success(res.message);
            this.loadData();
          } else {
            this.$message.warning(res.message);
          }
        })
      },
      handleDeptRole(record){
        if(this.currentDeptId != ''){
          this.$refs.deptRoleUser.add(record,this.currentDeptId);
          this.$refs.deptRoleUser.title = "部门角色分配";
        }else{
          this.$message.warning("请先选择一个部门!");
        }
      },
      handleChange(info){
        console.log(info)

        let {createBy,createTime,updateBy,updateTime,orgCode} = this.userInfo;
        let {uid,size} = info.file;
        let fileType = info.file.name.split('.')[1]
        let fileTitle = info.file.name;
        let fileMixName = info.file.response.message.split('/')[1];
        // let filePath = 'temp/' + fileMixName;
        let filePath = info.file.response.message;

        let params = {};
        let obb = {};
        let obj = {};

        obb = {
          id:'',
          createBy,
          createTime,
          updateBy,
          updateTime,
          sysOrgCode:orgCode,
          fileCode:uid,
          fileTitle,
          eqpBelong:this.selectedKeysNode.title,
          filePath,
          fileMixName,
          fileTypes: fileType,
          fileSize: size,
          pid: this.selectedKeys[0],
          modelName:'文件挂接',
          eqpUid: this.selectedKeys[0]
        };

        obj = {
          id: '',
          createBy,
          createTime,
          updateBy,
          updateTime,
          sysOrgCode:orgCode,
          versionNo:'1.0',
        };

        params = {
          obj,
          obb
        }
debugger
        fileTransManageAdd(params).then(res => {
          if(res.success){
            this.$message.success(`${info.file.name} 上传成功!`);
            this.loadData();
          }else{
            this.$message.warning(`${info.file.name} ${res.message}`);
          }
        })

      },
      // changeFileList(info){
      //   let { fileList } = info
      //   this.fileList = [...fileList]
      // }



    }
  }
</script>
<style scoped>
  /** Button按钮间距 */
  .ant-btn {
    margin-left: 3px
  }

  /*.ant-card {*/
    /*margin-left: -30px;*/
    /*margin-right: -30px;*/
  /*}*/

  .table-page-search-wrapper {
    margin-top: -16px;
    margin-bottom: 16px;
  }
  /deep/ .ant-modal{
    padding-bottom: 0;
  }
</style>